﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using XiAnAirport.DAL;
using XiAnAirport.ElevatorWebSocket;
using XiAnAirport.Models;

namespace XiAnAirport.BUS
{
    public class InspectionPlanBUS
    {
        public ResponseMessage AddPlan(InspectionPlanInfo planinfo)
        {
            InspectionPlanDAL da = new InspectionPlanDAL();
            ResponseMessage message = new ResponseMessage();

            try
            {
                if (string.IsNullOrEmpty(planinfo.preParationTime))
                {
                    planinfo.preParationTime = "null";
                }
                else
                {
                    planinfo.preParationTime = string.Format("'{0}'", Convert.ToDateTime(planinfo.preParationTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(planinfo.receiveTime))
                {
                    planinfo.receiveTime = "null";
                }
                else
                {
                    planinfo.receiveTime = string.Format("'{0}'", Convert.ToDateTime(planinfo.receiveTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(planinfo.arriveTime))
                {
                    planinfo.arriveTime = "null";
                }
                else
                {
                    planinfo.arriveTime = string.Format("'{0}'", Convert.ToDateTime(planinfo.arriveTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(planinfo.completeTime))
                {
                    planinfo.completeTime = "null";
                }
                else
                {
                    planinfo.completeTime = string.Format("'{0}'", Convert.ToDateTime(planinfo.completeTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(planinfo.acceptanceTime))
                {
                    planinfo.acceptanceTime = "null";
                }
                else
                {
                    planinfo.acceptanceTime = string.Format("'{0}'", Convert.ToDateTime(planinfo.acceptanceTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }

                if (string.IsNullOrEmpty(planinfo.inspectionDatetime))
                {
                    planinfo.inspectionDatetime = "null";
                }
                else
                {
                    planinfo.inspectionDatetime = string.Format("'{0}'", Convert.ToDateTime(planinfo.inspectionDatetime).ToString("yyyy-MM-dd HH:mm:ss"));
                }

                if (string.IsNullOrEmpty(planinfo.inspectionNo))
                {
                    planinfo.inspectionNo = GetWorkNo();
                }
                string result = da.AddPlan(planinfo);
                if (result == "success")
                {
                    InitWorkOrder();
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 0;
                    message.errmsg = "新增巡检工单失败";
                    message.data = null;
                    message.total = 1;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "新增巡检工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("新增巡检工单" + e.ToString());
            }
            return message;
        }

        public ResponseMessage EditPlan(InspectionPlanInfo planinfo)
        {
            InspectionPlanDAL da = new InspectionPlanDAL();
            ResponseMessage message = new ResponseMessage();
            try
            {
                if (string.IsNullOrEmpty(planinfo.preParationTime))
                {
                    planinfo.preParationTime = "null";
                }
                else
                {
                    planinfo.preParationTime = string.Format("'{0}'", Convert.ToDateTime(planinfo.preParationTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(planinfo.receiveTime))
                {
                    planinfo.receiveTime = "null";
                }
                else
                {
                    planinfo.receiveTime = string.Format("'{0}'", Convert.ToDateTime(planinfo.receiveTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(planinfo.arriveTime))
                {
                    planinfo.arriveTime = "null";
                }
                else
                {
                    planinfo.arriveTime = string.Format("'{0}'", Convert.ToDateTime(planinfo.arriveTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(planinfo.completeTime))
                {
                    planinfo.completeTime = "null";
                }
                else
                {
                    planinfo.completeTime = string.Format("'{0}'", Convert.ToDateTime(planinfo.completeTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                if (string.IsNullOrEmpty(planinfo.acceptanceTime))
                {
                    planinfo.acceptanceTime = "null";
                }
                else
                {
                    planinfo.acceptanceTime = string.Format("'{0}'", Convert.ToDateTime(planinfo.acceptanceTime).ToString("yyyy-MM-dd HH:mm:ss"));
                }

                if (string.IsNullOrEmpty(planinfo.inspectionDatetime))
                {
                    planinfo.inspectionDatetime = "null";
                }
                else
                {
                    planinfo.inspectionDatetime = string.Format("'{0}'", Convert.ToDateTime(planinfo.inspectionDatetime).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                string result = da.EditPlan(planinfo);

                if (result.Contains("success"))
                {
                    InitWorkOrder();
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                    message.data = null;
                    message.total = 0;

                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "修改巡检工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("修改巡检工单" + e.ToString());
            }
            return message;
        }

        public ResponseMessage LoadPlan(int planid)
        {
            InspectionPlanDAL da = new InspectionPlanDAL();
            ResponseMessage message = new ResponseMessage();
            try
            {
                InspectionPlanInfo content = da.LoadPlan(planid);

                if (content != null)
                {
                    if (!string.IsNullOrEmpty(content.inspectionDatetime))
                    {
                        content.inspectionDatetime = Convert.ToDateTime(content.inspectionDatetime).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    if (!string.IsNullOrEmpty(content.receiveTime))
                    {
                        content.receiveTime = Convert.ToDateTime(content.receiveTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    if (!string.IsNullOrEmpty(content.arriveTime))
                    {
                        content.arriveTime = Convert.ToDateTime(content.arriveTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    if (!string.IsNullOrEmpty(content.completeTime))
                    {
                        content.completeTime = Convert.ToDateTime(content.completeTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }

                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = content;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "未查询到相关信息";
                    message.data = null;
                    message.total = 0;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "载入巡检工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("载入巡检工单" + e.ToString());
            }
            return message;
        }

        public ResponseMessage QueryPlan(InspectionPlanInfo planinfo)
        {
            ResponseMessage message = new ResponseMessage();
            InspectionPlanDAL da = new InspectionPlanDAL();
            MaintainDAL maintainDAL = new MaintainDAL();
            try
            {
                List<InspectionPlanInfo> content = da.QueryPlan(planinfo);

                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
                message.total = da.QueryPlanCount(planinfo);
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询巡检工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询巡检工单" + e.ToString());
            }
            return message;
        }

        public ResponseMessage QueryInspectionHistory(InspectionPlanInfo planinfo)
        {
            ResponseMessage message = new ResponseMessage();
            InspectionPlanDAL da = new InspectionPlanDAL();
            try
            {
                List<InspectionPlanInfo> content = da.QueryInspectionHistory(planinfo);

                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
                message.total = da.QueryInspectionHistoryCount(planinfo);
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询历史巡检工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询历史巡检工单" + e.ToString());
            }
            return message;
        }

        public ResponseMessage GetWorkOrderStateList()
        {
            ResponseMessage message = new ResponseMessage();
            InspectionPlanDAL da = new InspectionPlanDAL();
            try
            {
                List<WorkorderState> content = da.GetWorkOrderStateList();

                message.errcode = 0;
                message.errmsg = "";
                message.data = content;

            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "获取巡检工单状态";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("获取巡检工单状态" + e.ToString());
            }
            return message;
        }

        public ResponseMessage DelPlan(int planid)
        {
            InspectionPlanDAL da = new InspectionPlanDAL();
            ResponseMessage message = new ResponseMessage();
            string result = string.Empty;
            try
            {
                result = da.DelPlan(planid);

                if (result.Contains("success"))
                {
                    InitWorkOrder();
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                    message.data = null;
                    message.total = 0;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "删除巡检工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("删除巡检工单" + e.ToString());
            }
            return message;
        }

        public string GetWorkNo()
        {
            while (true)
            {
                Random rd = new Random();
                int num = rd.Next(1, 9999);
                string orderNO = DateTime.Now.ToString("yyMMdd") + num.ToString().PadLeft(4, '0');
                if (CheckWorkNo(orderNO))
                {
                    return orderNO;
                }
            }
        }

        public bool CheckWorkNo(string orderNO)
        {
            InspectionPlanDAL inspectionPlanDAL = new InspectionPlanDAL();
            try
            {
                string number = inspectionPlanDAL.CheckWorkNo(orderNO);
                if (string.IsNullOrEmpty(number))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public ResponseMessage ExportPlan(InspectionPlanInfo inspectionPlan, string path)
        {
            ResponseMessage response = new ResponseMessage();
            try
            {
                InspectionPlanDAL inspectionPlanDAL = new InspectionPlanDAL();
                List<InspectionPlanInfo> list = inspectionPlanDAL.QueryPlan(inspectionPlan);
                if (list.Count < 65536)
                {
                    string sFileName = "巡检工单.xlsx";

                    FileInfo file = new FileInfo(Path.Combine(path, sFileName));

                    file.Delete();
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (ExcelPackage package = new ExcelPackage(file))

                    {
                        // 添加worksheet

                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("巡检工单");

                        //添加头
                        worksheet.Cells[1, 1].Value = "巡检编号";
                        worksheet.Cells[1, 2].Value = "电梯名称";
                        worksheet.Cells[1, 3].Value = "设备位置";
                        worksheet.Cells[1, 4].Value = "巡检日期";
                        worksheet.Cells[1, 5].Value = "工单状态";

                        //添加值

                        for (int i = 0; i < list.Count; i++)
                        {
                            InspectionPlanInfo inspectionPlanInfo = list[i];
                            worksheet.Cells[i + 2, 1].Value = inspectionPlanInfo.inspectionNo;
                            worksheet.Cells[i + 2, 2].Value = inspectionPlanInfo.elevatorName;
                            worksheet.Cells[i + 2, 3].Value = inspectionPlan.mainAreaName + "-" + inspectionPlanInfo.areaName;
                            worksheet.Cells[i + 2, 4].Value = Convert.ToDateTime(inspectionPlan.inspectionDatetime).ToString("yyyy/MM/dd");
                            worksheet.Cells[i + 2, 5].Value = inspectionPlan.workorderStateName;
                        }
                        package.Save();

                    }
                    response.errcode = 0;
                    response.errmsg = "";
                    response.data = "/" + sFileName;
                }
                else
                {
                    response.errcode = 1;
                    response.errmsg = "数据量超过65535条，无法导出";
                }

            }
            catch (Exception ex)
            {
                response.errcode = 1;
                response.errmsg = "导出失败";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导出巡检工单";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("导出巡检工单" + ex.ToString());
            }
            return response;
        }

        public ResponseMessage GenerateInspectionNo()
        {
            ResponseMessage message = new ResponseMessage();
            string workorder = GetWorkNo();
            message.data = workorder;
            return message;
        }

        public ResponseMessage ExportPlanHistory(InspectionPlanInfo inspectionPlan, string path)
        {
            ResponseMessage response = new ResponseMessage();
            try
            {
                InspectionPlanDAL inspectionPlanDAL = new InspectionPlanDAL();
                List<InspectionPlanInfo> list = new List<InspectionPlanInfo>();
                if (string.IsNullOrEmpty(inspectionPlan.ids))
                {
                    if (inspectionPlan.type == 0)//工单
                    {
                        list = inspectionPlanDAL.QueryPlan(inspectionPlan);
                    }
                    else//历史
                    {
                        list = inspectionPlanDAL.QueryInspectionHistory(inspectionPlan);
                    }
                }
                else
                {
                    list = inspectionPlanDAL.QueryInspectionHistoryByIds(inspectionPlan);
                }
                if (list.Count < 65536)
                {
                    string sFileName = "巡检工单.xlsx";

                    FileInfo file = new FileInfo(Path.Combine(path, sFileName));

                    file.Delete();
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (ExcelPackage package = new ExcelPackage(file))

                    {
                        // 添加worksheet

                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("巡检工单");

                        //添加头
                        worksheet.Cells[1, 1].Value = "巡检编号";
                        worksheet.Cells[1, 2].Value = "设备名称";
                        worksheet.Cells[1, 3].Value = "设备编号";
                        worksheet.Cells[1, 4].Value = "设备位置";
                        worksheet.Cells[1, 5].Value = "巡检日期";
                        worksheet.Cells[1, 6].Value = "工单状态";
                        worksheet.Cells[1, 7].Value = "制单时间";
                        worksheet.Cells[1, 8].Value = "接收时间";
                        worksheet.Cells[1, 9].Value = "到达时间";
                        worksheet.Cells[1, 10].Value = "完成时间";
                        worksheet.Cells[1, 11].Value = "验收时间";
                        //添加值

                        for (int i = 0; i < list.Count; i++)
                        {
                            InspectionPlanInfo inspectionPlanInfo = list[i];
                            worksheet.Cells[i + 2, 1].Value = inspectionPlanInfo.inspectionNo;
                            worksheet.Cells[i + 2, 2].Value = inspectionPlanInfo.elevatorName;
                            worksheet.Cells[i + 2, 3].Value = inspectionPlanInfo.elevatorNo;
                            worksheet.Cells[i + 2, 4].Value = inspectionPlanInfo.mainAreaName + "-" + inspectionPlanInfo.areaName;
                            worksheet.Cells[i + 2, 5].Value = inspectionPlanInfo.inspectionDatetime == null ? "" : Convert.ToDateTime(inspectionPlanInfo.inspectionDatetime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 6].Value = inspectionPlanInfo.workorderStateName;
                            worksheet.Cells[i + 2, 7].Value = inspectionPlanInfo.preParationTime == null ? "" : Convert.ToDateTime(inspectionPlanInfo.preParationTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 8].Value = inspectionPlanInfo.receiveTime == null ? "" : Convert.ToDateTime(inspectionPlanInfo.receiveTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 9].Value = inspectionPlanInfo.arriveTime == null ? "" : Convert.ToDateTime(inspectionPlanInfo.arriveTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 10].Value = inspectionPlanInfo.completeTime == null ? "" : Convert.ToDateTime(inspectionPlanInfo.completeTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 11].Value = inspectionPlanInfo.acceptanceTime == null ? "" : Convert.ToDateTime(inspectionPlanInfo.acceptanceTime).ToString("yyyy/MM/dd HH:mm:ss");
                        }
                        package.Save();

                    }
                    response.errcode = 0;
                    response.errmsg = "";
                    response.data = "/" + sFileName;
                }
                else
                {
                    response.errcode = 1;
                    response.errmsg = "数据量超过65535条，无法导出";
                }

            }
            catch (Exception ex)
            {
                response.errcode = 1;
                response.errmsg = "导出失败";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导出巡检工单";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("导出巡检工单" + ex.ToString());
            }
            return response;
        }

        public ResponseMessage BatchDelPlan(string ids)
        {
            InspectionPlanDAL da = new InspectionPlanDAL();
            ResponseMessage message = new ResponseMessage();
            string result = string.Empty;
            try
            {
                result = da.BatchDelPlan(ids);

                if (result.Contains("success"))
                {
                    InitWorkOrder();
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                    message.data = null;
                    message.total = 0;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "批量删除巡检工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("批量删除巡检工单" + e.ToString());
            }
            return message;
        }

        public static void InitWorkOrder()
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                int inspection = 0;
                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        string type = string.Empty;
                        int datanum = 0;

                        mqttdata mqttdata = new mqttdata();

                        if (i == 0)
                        {
                            type = "inspectionTotal";
                            List<mqttdata> list = mqttDataDAL.QueryMqttdata("OrderIncomplete", "04", "KONE");
                            int old_value = (int)list.FirstOrDefault(x => x.dataType == "inspection").dataNum;
                            datanum = old_value + mqttDataDAL.QueryInspectionOrder();
                            inspection = datanum;
                        }
                        else if (i == 1)
                        {
                            type = "inspectionCompleted";
                            datanum = inspection - mqttDataDAL.QueryInCompleteInspectionOrder();
                        }

                        mqttdata.dataNum = datanum;
                        mqttdata.manufacturer = "KONE";
                        mqttdata.manufacturerId = "04";
                        mqttdata.topicType = "TodayProcess";
                        mqttdata.dataType = type;
                        bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, mqttdata.manufacturerId, type, mqttdata.topicType);

                        if (result)
                        {
                            mqttDataDAL.UpdateMqttData(mqttdata);
                        }
                        else
                        {
                            mqttDataDAL.AddMqttData(mqttdata);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                bool result_5 = PushNoticeMessage("Refresh").Result;
                bool result_6 = PushKoneHomeMessage("RefreshHomePage").Result;

            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "初始化工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("初始化工单" + e.ToString());
            }
        }

        public static async Task<bool> PushNoticeMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushNoticeMessage(message);
        }

        public static async Task<bool> PushKoneHomeMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushKoneHomeMessage(message);
        }
    }
}
